<?php
namespace Operations\Controller;
use Common\Controller\AdminbaseController;
use Library\Area;
use Library\CardCode;
use Think\Log;


class MaterialsController extends AdminbaseController {
	protected $card_model;
	protected $cards_list_model;
	protected $card_area_model;
	protected $card_detail_model;
	protected $groups_model;
	function _initialize() {
		parent::_initialize();
		$this->card_model= D("Card");
		$this->cards_list_model = D("CardsList");
		$this->events_model = D("Events");
		$this->card_area_model = D('card_area');
		$this->card_detail_model=D("CardDetail");
		$this->groups_model = D("Groups");
        $this->event_prize_pool_model = D('event_prize_pool');

        //dump(C("CARD_STATUS_ENUM.CARD_STATUS_ONLINE"));exit;
	}
	function index(){
		$this->_lists();
		$this->display();
	}

	function add(){
        $this->_view_add_card();
		$this->_view_add_area();
		$this->_view_add_group();
		$this->display();
	}

	function add_materials(){
		//var_dump($_POST);exit;
		if (IS_POST) {
			if(!get_current_admin_id()){
				/* 这里面添加权限判断
				 */
				$this->error(sp_get_current_user()."您没有权限");
			}
			if(!I("post.card_name")){
				$this->error("请填写物料名称");
			}
			if(!I("post.card_intro")){
				$this->error("请填物料简介");
			}
			if(!I("post.card_type")){
				$this->error("请选择投放类型");
			}
			if ($_POST['card_type'] != 1) {
				$_POST['min_money'] = 0;
				$_POST['max_money'] = 0;
			}
			if (I('post.card_type') == 2 || I('post.card_type') == 5) {
				if(!I('post.password')){
					$this->error("请填写核销密码");
				}
			}else{
				$_POST['password'] = 0;
			}

			if(!is_numeric(I('post.card_count')) ||
				!is_numeric(I('post.min_money')) ||
				!is_numeric(I('post.max_money')) ||
				!is_numeric(I('post.day_count_limit_by_user')) ||
				!is_numeric(I('post.count_limit_by_user'))
				){
				$this->error("您输入的内容不是数字，请核对");
			}
			$_POST['card_status'] = 5;
			$_POST['created_at'] = date("Y-m-d H:i:s",time());
            $_POST['updated_at'] = date("Y-m-d H:i:s",time());
			$_POST['created_by'] = get_current_admin_id();
			$_POST['bind_location'] = $_POST['areas'][es][1];
			$_POST['userid'] = get_current_admin_id();
			$_POST['ugid'] = get_current_adminug_id();
			$_POST['external_cardid'] = I('post.wxcard');

			if (isset($_POST['areas'][es][1]) && !empty($_POST['areas'][es][1])) {
				$areaInfo = explode('|||', $_POST['areas'][es][1]);
				if ($areaInfo) {
					$areaIdList = explode(',', $areaInfo[0]);
				}
			}

			if($_FILES){
				$Aliyun = new \Aliyun\Controller\AliyunController();
				$imgs = $Aliyun->save($_FILES["card_icon"],'img/'.CONTROLLER_NAME);
				if(!$imgs['error']){
					$_POST['card_icon'] =$imgs['path'].$imgs['name'];
				}else{
					$this->error('图像上传失败');
				}
			}

            $card_id = $this->card_model->add($_POST);

			//奥运活动
			if (isset($_POST['prizes_grade'])) {
				$huodongExtend['card_id'] = $card_id;
				$huodongExtend['prizes_grade'] = $_POST['prizes_grade'];
				$card_huodong_extend_model = D('card_huodong_extend');
				$result = $card_huodong_extend_model->add($huodongExtend);
				if (!$result) {
					Log::record('card_huodong_extend_model add fail'. json_encode($huodongExtend));
				}
			}

			if ($card_id) {
				$areaData = array();
				if ($areaIdList) {
					foreach ($areaIdList as $area) {
						$data = array();
						$data['card_id'] = $card_id;
						$data['type'] = 0;
						$data['area_id'] = $area;
						$areaData[] = $data;
					}
				}
				if (I('post.group')) {
					foreach (I('post.groups') as $k => $id) {
						$groups['card_id'] = $card_id;
						$groups['type'] = 2;
						$groups['area_id'] = $id;
						$areaData[] = $groups;
					}
					foreach (I('post.customGroups') as $k => $id) {
						$customGroups['card_id'] = $card_id;
						$customGroups['type'] = 1;
						$customGroups['area_id'] = $id;
						$areaData[] = $customGroups;
					}
					if (!I('post.groups') && !I('post.customGroups')) {
						$groups['card_id'] = $card_id;
						$groups['type'] = 2;
						$groups['area_id'] = 0;   //0 代表没有限定物料的标签
						$areaData[] = $groups;
					}
				} else {
					$groups['card_id'] = $card_id;
					$groups['type'] = 2;
					$groups['area_id'] = 0;   //0 代表没有限定物料的标签
					$areaData[] = $groups;
				}
				if (!empty($areaData)) {
					$this->card_area_model->addALL($areaData);
				}

				if ($_POST['card_type'] == 2 || $_POST['card_type'] == 5) {
					//插入卡券详情表
					$cardDetail['card_id'] = $card_id;
					$cardDetail['password'] = $_POST['password'];
					$cardDetail['card_sdate'] = $_POST['card_sdate'];
					$cardDetail['card_edate'] = $_POST['card_edate'];
					$cardDetail['open_time_type'] = $_POST['open_time_type'];
                    if ($cardDetail['open_time_type'] == '') {
                        $cardDetail['open_time_type'] = 1;
                    }
					if ($cardDetail['open_time_type'] == 2) {
						$cardDetail['open_time_day'] = implode(',', $_POST['open_time_day']);
						if ($_POST['open_time_start1'] && $_POST['open_time_end1']) {
							$period['start'] = $_POST['open_time_start1'];
							$period['end'] = $_POST['open_time_end1'];
							$openPeriod[] = $period;
						}
						if ($_POST['open_time_start2'] && $_POST['open_time_end2']) {
							$period['start'] = $_POST['open_time_start2'];
							$period['end'] = $_POST['open_time_end2'];
							$openPeriod[] = $period;
						}
						$cardDetail['open_time_period'] = json_encode($openPeriod);
					}
					$cardDetail['user_notice'] = $_POST['user_notice'];
					$result = $this->card_detail_model->add($cardDetail);
					Log::record('card_detail_model add'.$result);
				}
				//AJSON 页面返回之后后台数据继续运行  不需要就不传
				$this->success("添加成功！",U('Materials/index'),0,'AJSON');
                if ($_POST['card_type'] == 2 || $_POST['card_type'] == 5) { //核销类和实体类 生成核销码
					$card = \Library\CardCode::getInstance();
                    $card->create_cards($card_id, I("post.card_count"));
                }
    			$this->card_model->where(array('id'=>$card_id))->setField('card_status','0');
			} else {
				$this->error("添加失败！");
			}
		}
	}

    public function preview(){
        $id =  intval(I("get.id"));

        $card = $this->card_model->where("id=$id")->find();
        if ($card) {
            $area = explode('|||', $card['bind_location']);
            $card['areaNameList'] = $area[1];
        }
        $customGroups = $this->card_area_model->where(array('card_id'=>$id,'type'=>1))->select();
        $groups = $this->card_area_model->where(array('card_id'=>$id,'type'=>2))->select();
        $cardDetail = $this->card_detail_model->where(array('card_id'=>$id))->find();
        $huodong = D('card_huodong_extend')->where(array('card_id'=>$id))->find();

        if ($cardDetail) {
            if ($cardDetail['open_time_type'] == 2) {
                if ($cardDetail['open_time_day'] != '') {
                    $cardDetail['open_time_day'] = explode(',',  $cardDetail['open_time_day']);
                }
                if ($cardDetail['open_time_period'] != '') {
                    $cardDetail['open_time_period'] = json_decode($cardDetail['open_time_period'], true);
                }
            }
        }

        //var_dump($cardDetail);exit;
        $this->_view_add_card();
        $this->_view_add_area();
        $this->_view_add_group();
        $this->assign("card", $card);
        $this->assign("card_groups", $groups);
        $this->assign("card_customGroups", $customGroups);
        $this->assign("card_detail", $cardDetail);
        $this->assign("card_huodong", $huodong);
        $this->assign("urlimg", C('IMG_PATH'));
        $this->display();
    }

	public function edit(){
		$id =  intval(I("get.id"));

		$card = $this->card_model->where("id=$id")->find();
		if ($card) {
			$area = explode('|||', $card['bind_location']);
			$card['areaNameList'] = $area[1];
		}
		$customGroups = $this->card_area_model->where(array('card_id'=>$id,'type'=>1))->select();
		$groups = $this->card_area_model->where(array('card_id'=>$id,'type'=>2))->select();
		$cardDetail = $this->card_detail_model->where(array('card_id'=>$id))->find();
		$huodong = D('card_huodong_extend')->where(array('card_id'=>$id))->find();

		if ($cardDetail) {
			if ($cardDetail['open_time_type'] == 2) {
				if ($cardDetail['open_time_day'] != '') {
					$cardDetail['open_time_day'] = explode(',',  $cardDetail['open_time_day']);
				}
				if ($cardDetail['open_time_period'] != '') {
					$cardDetail['open_time_period'] = json_decode($cardDetail['open_time_period'], true);
				}
			}
		}
		//var_dump($cardDetail);exit;
        $this->_view_add_card();
		$this->_view_add_area();
		$this->_view_add_group();
		$this->assign("card", $card);
		$this->assign("card_groups", $groups);
		$this->assign("card_customGroups", $customGroups);
		$this->assign("card_detail", $cardDetail);
		$this->assign("card_huodong", $huodong);
		$this->assign("urlimg", C('IMG_PATH'));
		$this->display();
	}

	public function edit_materials(){
		if (IS_POST) {
			if(!I("post.card_name")){
				$this->error("请填写物料名称");
			}
			if(!I("post.card_intro")){
				$this->error("请填物料简介");
			}
			if ($_POST['card_type'] != 1) {
				$_POST['min_money'] = 0;
				$_POST['max_money'] = 0;
			}
			if (I('post.card_type') != 2 || I('post.card_type') != 5) {
				$_POST['password'] = 0;
			}
            $_POST['card_status'] = 0;

			if( !is_numeric(I('post.min_money')) ||
				!is_numeric(I('post.max_money')) ||
				!is_numeric(I('post.day_count_limit_by_user')) ||
				!is_numeric(I('post.count_limit_by_user'))
				){
				$this->error("您输入的内容不是数字，请核对");
			}
			$_POST['created_at'] = date("Y-m-d H:i:s",time());
			$_POST['updated_at'] = date("Y-m-d H:i:s",time());
            if (isset($_POST['areas'])) {
                $_POST['bind_location'] = $_POST['areas'][es][1];
                if (isset($_POST['areas'][es][1]) && !empty($_POST['areas'][es][1])) {
                    $areaInfo = explode('|||', $_POST['areas'][es][1]);
                    if ($areaInfo) {
                        $areaIdList = explode(',', $areaInfo[0]);
                    }
                }
            }
			$_POST['external_cardid'] = I('post.wxcard');
            unset($_POST['card_count']); //暂时禁止修改数量
			unset($_POST['password']); //暂时禁止修改核销密码

			if($_FILES){
                if (!empty($_FILES['newcard_icon'])) {
                    $Aliyun = new \Aliyun\Controller\AliyunController();
                    if (!empty($_POST['card_icon'])) {
                        $Aliyun->delete($_POST['card_icon']);
                    }
                    $imgs = $Aliyun->save($_FILES["newcard_icon"],'img/'.CONTROLLER_NAME);
                    if(!$imgs['error']){
                        $_POST['card_icon'] =$imgs['path'].$imgs['name'];
                    }else{
                        Log::record('img uplaod to aliyun fail'.$_POST['card_icon']);
                        $this->error('图像上传失败');
                    }
                }
                if ($_FILES['code_file']) {
                    $this->importCardCode($_POST['id'], $_FILES['code_file']['tmp_name']);
                }
			}

			$this->card_model->startTrans();
			if ($this->card_model->save($_POST)) {
                //奥运活动
                if (isset($_POST['prizes_grade'])) {
                    $card_huodong_extend_model = D('card_huodong_extend');
                    //$card_huodong_extend_model->where('card_id='.$_POST['id'])->delete();
                    $huodongExtend['id'] = $_POST['huodong_extend_id'];
                    $huodongExtend['card_id'] = $_POST['id'];
                    $huodongExtend['prizes_grade'] = $_POST['prizes_grade'];
                    $result = $card_huodong_extend_model->add($huodongExtend, array(), true);
                    if (!$result) {
                        Log::record('card_huodong_extend_model add fail'. json_encode($huodongExtend));
                    }
                }

                if ($_POST['card_type'] == 2 || $_POST['card_type'] == 5) {
                    //插入卡券详情表
                    $cardDetail['id'] = $_POST['card_detail_id'];
                    $cardDetail['card_id'] = $_POST['id'];
                    $cardDetail['password'] = $_POST['password'];
                    $cardDetail['open_time_type'] = $_POST['open_time_type'];
                    if ($_POST['card_sdate'] == '' || $_POST['card_edate'] == '') {
                        $cardDetail['card_sdate'] = array('exp','null');
                        $cardDetail['card_edate'] = array('exp','null');
                    } else {
                        $cardDetail['card_sdate'] = $_POST['card_sdate'];
                        $cardDetail['card_edate'] = $_POST['card_edate'];
                    }
                    if ($cardDetail['open_time_type'] == '') {
                        $cardDetail['open_time_type'] = 1;
                    }
                    if ($cardDetail['open_time_type'] == 2) {
                        $cardDetail['open_time_day'] = implode(',', $_POST['open_time_day']);
                        if ($_POST['open_time_start1'] && $_POST['open_time_end1']) {
                            $period['start'] = $_POST['open_time_start1'];
                            $period['end'] = $_POST['open_time_end1'];
                            $openPeriod[] = $period;
                        }
                        if ($_POST['open_time_start2'] && $_POST['open_time_end2']) {
                            $period['start'] = $_POST['open_time_start2'];
                            $period['end'] = $_POST['open_time_end2'];
                            $openPeriod[] = $period;
                        }
                        $cardDetail['open_time_period'] = json_encode($openPeriod);
                    }
                    $cardDetail['user_notice'] = $_POST['user_notice'];
                    $result = $this->card_detail_model->add($cardDetail, array(), true);
                    Log::record('card_detail_model add'.$result);
                }

				$this->card_area_model->where('card_id='.$_POST['id'])->delete();
				$areaData = array();
				foreach ($areaIdList as $area) {
					$data = array();
					$data['card_id'] = $_POST['id'];
					$data['type'] = 0;
					$data['area_id'] = $area;
					$areaData[] = $data;
				}
				if(I('post.group')){
					foreach(I('post.groups') as $k=>$id){
						$groups['card_id'] = $_POST['id'];
						$groups['type'] = 2;
						$groups['area_id'] =$id;
						$areaData[] = $groups;
					}
					foreach(I('post.customGroups') as $k=>$id){
						$customGroups['card_id'] = $_POST['id'];
						$customGroups['type'] = 1;
						$customGroups['area_id'] =$id;
						$areaData[] = $customGroups;
					}
					if (!I('post.groups') && !I('post.customGroups')) {
						$groups['card_id'] = $_POST['id'];
						$groups['type'] = 2;
						$groups['area_id'] =0;   //0 代表没有限定物料的标签
						$areaData[] = $groups;
					}
				} else {
					$groups['card_id'] = $_POST['id'];
					$groups['type'] = 2;
					$groups['area_id'] =0;   //0 代表没有限定物料的标签
					$areaData[] = $groups;
				}

				if (!empty($areaData)) {
					$this->card_area_model->addALL($areaData);
				}
				$this->card_model->commit();
				$this->success("修改卡券信息成功！",U('Materials/index'));
			} else {
				$this->card_model->rollback();
				$this->error("修改卡券信息失败！");
			}
		}
	}

    private function importCardCode($cardId, $cardCodeCsvFile) {
        ini_set("auto_detect_line_endings", true);
        $file = fopen($cardCodeCsvFile, "r");
        $codeNum = 0;
        while (!feof($file)) {
            $line = fgetcsv($file, 0, ',');
            if (!$line) {
                break;
            }
            $codeNum++;
            $cardCode = array_shift($line);
            $data['card_id'] = $cardId;
            $data['card_number'] = $cardCode;
            $data['code_type'] = 1;
            $data['created_at'] = date("Y-m-d H:i:s", time());
            $dataList[] = $data;
            if ($codeNum == 1000) {
                $this->cards_list_model->startTrans();
                try {
                    $result = $this->cards_list_model->addALL($dataList);
                     Log::record('$result' . $result);
                    $this->card_model->where('id = ' . $cardId)->setInc('card_count', $codeNum);
                } catch (\Exception $e) {
                    Log::record(__FUNCTION__ . ' error ' . $e->getMessage());
                    $this->cards_list_model->rollback();
                    $codeNum = 0;
                    unset($dataList);
                    return false;
                }
                $codeNum = 0;
                unset($dataList);
                $this->cards_list_model->commit();
            }
        }
        if ($codeNum > 0 && count($dataList) > 0) {
            $this->cards_list_model->startTrans();
            try {
                $result = $this->cards_list_model->addALL($dataList);
                Log::record('$result' . $result);
                $this->card_model->where('id = ' . $cardId)->setInc('card_count', $codeNum);
            } catch (\Exception $e) {
                Log::record(__FUNCTION__ . ' error ' . $e->getMessage());
                $this->cards_list_model->rollback();
                return false;
            }
            $codeNum = 0;
            unset($dataList);
            $this->cards_list_model->commit();
        }
        fclose($file);
        return true;
    }

    private function _view_add_card() {
		$this->assign('prizesGradeList', C('PRIZES_GRADE')); //物料类型列表
        $this->assign('cardTypeList', C('CARD_TYPE')); //物料类型列表
        $this->assign('cardStatusList', C('CARD_STATUS')); //物料类型列表
    }
	private function _view_add_area() {
		$area = Area::getInstance();
		$regions = $area->getThreeRegions();

		$this->assign('regions', $regions); //物料归属列表
	}

	private function _view_add_group() {
		$customGroupsModel = $this->groups_model->where(array('status'=>1))->select();

		$groupsModel = C('SHOP_TYPE');
		$this->assign("customGroups", $customGroupsModel);
		$this->assign("groups", $groupsModel);
	}

	private  function _lists(){
		$userid = get_current_admin_id();
		$roleid =  get_current_adminrole_id();
		if (!$userId) {
			if ($roleid >= 20) {
				$search[] = array('userid'=>$userid);
			}
		}
		/*if(!get_current_adminug_id() && get_current_adminrole_id() > 9){
            $search[] = array('id'=>0);
            $_GET['id'] = 0;
		}elseif(get_current_adminug_id() && get_current_adminrole_id() > 9){
            $search[] = array('ugid'=>get_current_adminug_id());
            $_GET['ugid'] = get_current_adminug_id();
		}*/

		if(I('param.')){
            if(I('param.card_type')){
                    $search[] = array('card_type'=>I('param.card_type'));
                    $_GET['card_type'] = I('param.card_type');
            }
            if(I('param.start_time')){
                    $search[] = array('date(created_at)'=>array('egt',I('param.start_time')));
                    $_GET['start_time'] = I('param.start_time');
            }
            if(I('param.end_time')){
                    $search[] = array('date(created_at)'=>array('elt',I('param.end_time')));
                    $_GET['end_time'] = I('param.end_time');
            }
            if(I('param.keyword')){
                    $search[] = array('card_name'=>array("like","%".I('param.keyword')."%"));
                    $_GET['keyword'] = I('param.keyword');
            }
		}

		$count=$this->card_model
		->where($search)
		->count();
		$page = $this->page($count, 50);
		$card=$this->card_model
		->where($search)
		->limit($page->firstRow . ',' . $page->listRows)
		->order("id desc")->select();
		if($card){
			foreach($card as$cuser){
				$uid[] =$cuser['create_by'];
			}
			$users=M("users")->field("id,user_login")->where(array('id'=>array('in',$uid)))->select();
		}
        $openEvents = $this->events_model->field('id, event_name')->where('event_status = 2 and open_level = 2')->select();

        $this->_view_add_card();
        $this->assign("openEvents", $openEvents);
		$this->assign("users", $users);
		$this->assign("Page", $page->show('Admin'));
		$this->assign("current_page", $page->GetCurrentPage());
		unset($_GET[C('VAR_URL_PARAMS')]);
		$this->assign("cards", $card);
        $this->assign("card_status", C('CARD_STATUS'));
		$this->assign("count", $count);
        $this->assign('web_domain', WEB_DOMAIN);
	}
    function delete(){
		$id =  intval(I("get.id"));
		$events = $this->events_model->where(array("bind_cards"=>array("like","%$id%")))->find();
		if(!$events){
			$img = $this->card_model->where("id=$id")->find();
			if($img['card_icon']){
				$Aliyun = new \Aliyun\Controller\AliyunController();
				$Aliyun->delete($img['card_icon']);
			}
			$card = $this->card_model->delete($id);
			$this->cards_list_model->where("card_id=$id")->delete();
			$this->success("物料删除成功");
		}else{
			$this->error("物料已经被包含在活动 < ".$events['event_name']." > 中，不可删除");
		}
    }
    public function pub(){
        if (I("post.id")) {
            $rst = $this->card_model->where(array('id'=>I("post.id"), 'card_status' => array(IN , '0, 1') ))->setField('card_status','2');
            if ($rst && isset($_POST['events'])) {
                foreach ($_POST['events'] as $eventId) {
                    $this->event_prize_pool_model->where(array('event_id'=> $eventId, 'card_id'=>I("post.id")))->delete();
                    $prize['event_id'] =  $eventId;
                    $prize['card_id'] = I("post.id");
                    $prize['weight'] = 10;
                    $prizeList[] = $prize;
                }
                $rst = $this->event_prize_pool_model->addAll($prizeList);
            }
            if ($rst) {
                $this->success("物料发布成功！");
            } else {
                $this->error('物料发布失败！');
            }
        } else {
            //$this->error($this->card_model->getError());
            $this->error('物料发布失败！');
        }
    }
	public function up(){
    	if (I("get.id")) {
            $where['id'] = I("request.id");
            $where['card_status'] = 4;
            $data['card_status'] = 1;
    		$rst = $this->card_model->where($where)->save($data);
    		if ($rst) {
    			$this->success("物料重新开启成功！");
    		} else {
    			$this->error('物料重新开启失败！');
    		}
    	} else {
			$this->error($this->card_model->getError());
    	}
    }
    public function down(){
    	if (I("get.id")) {
    		$rst = $this->card_model->where(array('id'=>I("get.id"), 'card_status' => 1 ))->setField('card_status','4');
    		if ($rst) {
    			$this->success("物料暂停成功！");
    		} else {
    			$this->error('物料暂停失败！');
    		}
    	} else {
			$this->error($this->card_model->getError());
    	}
    }
    public function disable(){
        if (I("get.id")) {
            $rst = $this->card_model->where(array('id'=>I("get.id"), 'card_status' => 1 ))->setField('card_status','11');
            if ($rst) {
                $this->success("物料禁用成功！");
            } else {
                $this->error('物料禁用失败! ');
            }
        } else {
            $this->error($this->card_model->getError());
        }
    }
    public function valid(){
        if (I("request.id")) {
            $rst = $this->card_model->where(array('id'=>I("request.id"), 'card_status' => 11 ))->setField('card_status','1');
            if ($rst) {
                $this->success("物料禁用成功！");
            } else {
                $this->error('物料禁用失败! ');
            }
        } else {
            $this->error($this->card_model->getError());
        }
    }
	public function pass(){
		if (I("request.id")) {
            $where['id'] = I("request.id");
            $where['card_status'] = 2;
            $data['card_status'] = (int)1;
            if (I("request.reason")) {
                $data['reason'] = I("request.reason");
            }
            $rst = $this->card_model->where($where)->save($data);
			if ($rst) {
				$this->success('物料审核通过成功！', '', true);
			} else {
				//$this->error('物料审核通过失败! ', '', true);
				$this->error($this->card_model->getError().$this->card_model->getLastSql(), '', true);
			}
		} else {
			$this->error('物料审核通过失败, 参数错位! ', '', true);
		}
	}
	public function not_pass(){
		if (I("request.id")) {
            $where['id'] = I("request.id");
            $where['card_status'] = 2;
            $data['card_status'] = 3;
            $data['reason'] = I("request.reason");
            $rst = $this->card_model->where($where)->save($data);
			if ($rst) {
				$this->success('物料禁用成功！', '', true);
			} else {
				$this->error('物料禁用失败! ', '', true);
			}
		} else {
			$this->error($this->card_model->getError());
		}
	}
    public function del_img(){
    	if (I("get.id")) {
    		$event = $this->card_model->where(array('id'=>I("get.id")))->find();
			$img = $event[I("get.type")];
			$type =I("get.type");
			if($img){
				$Aliyun = new \Aliyun\Controller\AliyunController();
				$Aliyun->delete($img);
			}
    		if ($this->card_model->where(array('id'=>I("get.id")))->setField($type,'')) {
    			$this->success("图片删除成功！");
    		} else {
    			$this->error('图片删除失败！');
    		}
    	} else {
			$this->error($this->card_model->getError());
    	}
    }
	/*
	 * 卡券列表页面
	 */
    public function real(){
		if(I('param.')){
            if(I('param.id')){
                $search[] = array('yy_cards_list.card_id'=>I('param.id'));
                $_GET['id'] = I('param.id');
            }
            if(I('param.status')){
                $search[] = array('card_status'=>I('param.status'));
                $_GET['status'] = I('param.status');
            }
            if(I('param.start_time')){
                    $search[] = array('date(created_at)'=>array('egt',I('param.start_time')));
                    $_GET['start_time'] = I('param.start_time');
            }
            if(I('param.end_time')){
                    $search[] = array('date(created_at)'=>array('elt',I('param.end_time')));
                    $_GET['end_time'] = I('param.end_time');
            }
            if(I('param.keyword')){
                    $search[] = array('card_number'=>array("like","%".I('param.keyword')."%"));
                    $_GET['keyword'] = I('param.keyword');
            }
		}
		$where = 'yy_prizes_order.order_status is null  or yy_prizes_order.order_status = 0 or yy_prizes_order.order_status = 1 or yy_prizes_order.order_status = 2';

		$count=$this->cards_list_model
			->join('LEFT JOIN yy_prizes_order ON (yy_cards_list.card_id = yy_prizes_order.card_id AND yy_cards_list.card_number = yy_prizes_order.card_num)')
			->where($search)
			->where($where)
			->count();

/*		var_dump($count);
		var_dump($this->cards_list_model->getLastSql());*/
		$page = $this->page($count, 50);
		$cardslist=$this->cards_list_model
			->join('LEFT JOIN yy_prizes_order ON (yy_cards_list.card_id = yy_prizes_order.card_id AND yy_cards_list.card_number = yy_prizes_order.card_num)')
			->where($search)
			->where($where)
			->limit($page->firstRow . ',' . $page->listRows)
			->getField('yy_cards_list.id, yy_cards_list.card_number, yy_cards_list.created_at, yy_cards_list.card_status, yy_cards_list.card_id, yy_prizes_order.order_status');

        $this->_view_add_card();
		$this->assign("count", $count);
		$this->assign("Page", $page->show('Admin'));
		$this->assign("cards", $cards);
		$this->assign("cardslist", $cardslist);
		$this->display();
    }
	/*
	 * 后台卡券核销接口
	 */
    public function verification(){
		$cardCode = I("get.code");
		$cardId	= I("get.card_id");
    	if ($cardId && $cardCode) {
			$card = CardCode::getInstance();
    		if ($card->consume($cardId, $cardCode)) {
    			$this->success("卡券核销成功！");
    		} else {
    			$this->error('卡券核销失败！');
    		}
    	} else {
			$this->error('无效的卡券');
    	}
    }

	/*
	 * 设置卡券码状态 暂时未启用
	 */
	private function cardsup(){
    	if (I("get.id")) {
    		$data['card_status'] = 1;
    		$data['updated_at'] = date("Y-m-d H:i:s");
			$data['userid'] = get_current_admin_id();
    		if ($this->cards_list_model->where(array('id'=>I("get.id")))->save($data)) {
    			$this->success("卡券发放成功！");
    		} else {
    			$this->error('卡券发放失败！');
    		}
    	} else {
			$this->error($this->cards_list_model->getError());
    	}
    }
	/*
	 * 设置卡券码状态 暂时未启用
	 */
	private function cardsdown(){
    	if (I("get.id")) {
    		$data['card_status'] = 3;
    		$data['updated_at'] = date("Y-m-d H:i:s");
			$data['userid'] = get_current_admin_id();
    		if ($this->cards_list_model->where(array('id'=>I("get.id")))->save($data)) {
    			$this->success("卡券暂停成功！");
    		} else {
    			$this->error('卡券暂停失败！');
    		}
    	} else {
			$this->error($this->cards_list_model->getError());
    	}
    }
}
